<?php
/**
 * @特惠赚
 * Author: 小谢
 * Date: 2019-5-9
 */
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\response\Json;
use think\facade\Session;
use think\facade\Request;
class Base extends Controller {

    /**
     * 析构函数
     */
    function __construct() 
    {
        Session::start();
        header("Cache-control: private");
        $action = Request::action();//module、controller
        //过滤不需要登陆的行为
        if(in_array($action,array('login','logout','verify'))){
          return;
        }else{
          if(session('admin_id') > 0 ){
            $this->check_priv();//检查管理员菜单操作权限
          }else{
            $this->redirect('Admin/Admin/login');
          }
        }
    } 

    //检查管理员菜单操作权限
    public function check_priv()
    {
      $ctl = Request::controller();
      $act = Request::action();
      $act_list = session('act_list');
      //无需验证的操作
      $uneed_check = array('login','logout','vertifyHandle','vertify','imageUp','upload');
      if($ctl == 'Index' || $act_list == 'all'){
        //后台首页控制器无需验证,超级管理员无需验证
        return true;
      }elseif(request()->isAjax() || strpos($act,'ajax')!== false || in_array($act,$uneed_check)){
        //所有ajax请求不需要验证权限
        return true;
      }else{
        $right = M('system_menu')->where("id", "in", $act_list)->cache(true)->getField('right',true);

        $role_right = '';
        foreach ($right as $val){
            $role_right .= $val.',';
        }
        $role_right = explode(',', $role_right);
        //检查是否拥有此操作权限
        if(!in_array($ctl.'@'.$act, $role_right)){
            $this->error('您没有操作权限['.($ctl.'@'.$act).'],请联系超级管理员分配权限',U('Admin/Index/welcome'));
        }
      }
    }

    //权限组名称
    public function groupList() {
        $group =  M('right_group')->order('orderby ASC')->select();
        $data = [];
        if($group) {
           foreach ($group as $v) {
               $data[$v['ctl']] = trim($v['name']);
           }
        }
        return $data;
    }   
    
    //定义json格式
    public function ajaxReturn($data,$type = 'json'){                        
        exit(json_encode($data));
    }

    /**
     * @brief 短信使用场景
     */
    public function sendScene() {
        $data = array(
          '1'=>array('用户注册','验证码${code}，用户注册新账号, 请勿告诉他人，感谢您的支持!','regis_sms_enable'),
          '2'=>array('用户找回密码','验证码${code}，用于密码找回，如非本人操作，请及时检查账户安全','forget_pwd_sms_enable'),
          '3'=>array('用户登录' , '尊敬的用户，您的验证码为${code}, 请勿告诉他人','login_pwd_sms_enable')
        );
        return $data;
    }

}